package net.uman.framework.jms;

import java.io.Serializable;
import java.util.ArrayList;

import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.ObjectMessage;
import javax.jms.Session;

import net.uman.framework.modules.utils.PortalMessageObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.jms.support.converter.MessageConverter;

/**
 * JMS消息生产者.
 * 
 * 使用jmsTemplate将String消息分别发送到queue与topic.
 * 
 * @author eric Chen
 */
public class PortalMessageProducer {

    private static Logger logger = LoggerFactory.getLogger(PortalMessageProducer.class);
	private JmsTemplate jmsTemplate;
	private Destination notifyQueue;

	public void sendPortalMessage(ArrayList<PortalMessageObject> msg) {
	    
 		sendMessage(msg, notifyQueue);
		logger.debug("Portal message sending");
	}

	private void sendMessage(final ArrayList<PortalMessageObject> mess, Destination destination) {
	    jmsTemplate.send(destination, new MessageCreator() {
            public Message createMessage(Session session) throws JMSException {
                ObjectMessage msg = session.createObjectMessage();
                msg.setObject((Serializable)mess);
                MessageConverter converter = jmsTemplate.getMessageConverter();
                if (converter == null) {
                    throw new IllegalStateException("No 'messageConverter' specified. Check configuration of JmsTemplate.");
                }
                return converter.toMessage(msg, session);
            }
        });
	}

	public void setJmsTemplate(JmsTemplate jmsTemplate) {
		this.jmsTemplate = jmsTemplate;
	}

	public void setNotifyQueue(Destination notifyQueue) {
		this.notifyQueue = notifyQueue;
	}


}
